﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using SXICE.Core.Helpers;
using SXICE.Core.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SXICE.AdminAPI.Middlewares
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate next;

        public ExceptionHandlingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                RuntimeHelper.Resolve<ILog>().Error(ex);
                await context.Response.WriteAsync(ex.ToString());
            }
        }
    }

    public static class ExceptionHandlingMiddlewareExtention
    {
        public static void UseExceptionMiddleware(this IApplicationBuilder application)
        {
            application.UseMiddleware<ExceptionHandlingMiddleware>();
        }
    }
}
